package com.cp.config;

import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.Assert;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * Des:
 * Redis Key 默认按照服务名进行分类
 *
 * @author XL
 * @Date 2022/2/16 18:58
 */
public class CpKeyStringSerializer extends StringRedisSerializer {

    public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
    /**
     * 服务名称
     */
    private final String applicationName;

    public CpKeyStringSerializer(String applicationName) {
        Assert.notNull(applicationName, "服务名称不能为空");
        this.applicationName = applicationName;
    }

    /**
     * des:
     * 服务名作为包名
     *
     * @param key KEY值
     * @return {@link byte[] }
     * @author captain
     * @date 2022/2/16 19:08
     */
    @Override
    public byte[] serialize(String key) {
        Assert.notNull(key, "key不能为空");
        key = enhanceKey(key);
        return key.getBytes(DEFAULT_CHARSET);
    }


    /**
     * des:
     * 反序列化
     *
     * @param bytes 数组
     * @return {@link String }
     * @author captain
     * @date 2022/2/16 19:10
     */
    @Override
    public String deserialize(byte[] bytes) {
        return bytes == null ? null : reductionKey(new String(bytes, DEFAULT_CHARSET));
    }

    /**
     * des:
     * 增强key
     *
     * @param key 原始key
     * @return {@link String }
     * @author captain
     * @date 2022/2/16 19:12
     */
    public String enhanceKey(String key) {
        return applicationName + ":" + key;
    }

    /**
     * des:
     * 还原增强key
     *
     * @param enhanceKey 增强key
     * @return {@link String }
     * @author captain
     * @date 2022/2/16 19:22
     */
    public String reductionKey(String enhanceKey) {
        //如果存在2个以上,则说明key的组成为 applicationName:key1:k2
        String[] keyParts = enhanceKey.split(":");
        StringBuilder builder = new StringBuilder();
        if (keyParts.length == 1) {
            return keyParts[0];
        }

        if (keyParts.length > 2) {
            for (int i = 1; i < keyParts.length; i++) {
                if (i != keyParts.length - 1) {
                    builder.append(keyParts[i]).append(":");
                    continue;
                }
                builder.append(keyParts[i]);
            }
            return builder.toString();
        }

        return keyParts[1];
    }
}
